<template>
  <!-- 数字样机管理 -->
  <div class="digital-machine-manage">
    <div class="dmm-left">
      <LeftTree ref="leftTreeRef" :isGeneralFolderAndFile="true" :topAdd="true" :treeData="digitalMachineList"
        @handleAddNode="addModel" @nodeClick="nodeClick" :defaultExpandedKeys="defaultExpandedKeys"
        :currentNodeKey="currentNodeKey" :topAddMenu="right_menuList.rightMenuList_9"
        :folderMenu="right_menuList.rightMenuList_10" :fileMenu="right_menuList.rightMenuList_11"
        @handleMenuClick="handleMenuClick" @moveNodeOrder="moveNodeOrder">
      </LeftTree>
    </div>
    <div class="dmm-right">
      <FolderDetail v-if="isFolder" ref="folderRef" flag="digitalMachine" :nodeInfo="selectedNodeInfo"></FolderDetail>
      <DigitalMachineDetail v-if="isFile" ref="digitalMachineDetailRef" :nodeInfo="selectedNodeInfo">
      </DigitalMachineDetail>
    </div>
    <AddOrUpdateFolder ref="addOrUpdateFolderRef" @refresh="getDigitalMachineList"></AddOrUpdateFolder>
    <AddOrUpdateFile ref="addOrUpdateFileRef" @refresh="getDigitalMachineList"></AddOrUpdateFile>
  </div>
</template>

<script>
import { getDigitalMachineList } from "@/api/myspace/model-manage-tool/model-manage";
import LeftTree from "@/components/LeftTree/tree.vue";
import FolderDetail from "./components/folder-detail.vue";
import DigitalMachineDetail from "./components/digital-machine-manage/digital-machine-detail.vue";
import { mapState } from "vuex";
import AddOrUpdateFolder from "./components/digital-machine-manage/add-or-update-folder.vue";
import AddOrUpdateFile from "./components/digital-machine-manage/add-or-update-file.vue";
export default {
  data() {
    return {
      isFolder: false, // 是否展示文件夹详情
      isFile: false, // 是否展示文件详情
      selectedNodeInfo: {}, // 当前选中节点的信息
      digitalMachineList: [], // 数字样机列表
      defaultExpandedKeys: [], //树默认要展开的节点
      currentNodeKey: 0,
    };
  },
  components: {
    LeftTree,
    FolderDetail,
    DigitalMachineDetail,
    AddOrUpdateFolder,
    AddOrUpdateFile
  },
  computed: {
    ...mapState({
      right_menuList: (state) => state.modelManageTool.right_menuList,
      selectedNodeId: (state) => state.modelManageTool.machine.selectedNodeId,
      expandedNodeIds: (state) => state.modelManageTool.machine.expandedNodeIds,
    }),
  },
  async created() {
    await this.getDigitalMachineList();
    this.currentNodeKey = this.selectedNodeId;
    this.defaultExpandedKeys = this.expandedNodeIds;
    this.$nextTick(() => {
      this.$refs.leftTreeRef.$refs.treeRef.setCurrentKey(this.currentNodeKey)
    })
  },
  methods: {
    async getDigitalMachineList(newNodeId) {
      await getDigitalMachineList().then((response) => {
        if (response.code == 200) {
          this.digitalMachineList = response.data[0].commonTreeList;
          this.nodeClick(
            newNodeId ? this.recurNodeForTarget(this.digitalMachineList, newNodeId) :
              this.selectedNodeId ? this.recurNodeForTarget(this.digitalMachineList, this.selectedNodeId) :
                this.digitalMachineList[0])
        }
      });
    },
    // 递归获取当前树节点
    recurNodeForTarget(nodeArr, id) {
      for (let i = 0; i < nodeArr.length; i++) {
        if (nodeArr[i].id == id) {
          return nodeArr[i];
        } else {
          if (nodeArr[i].children && nodeArr[i].children.length > 0) {
            let node = this.recurNodeForTarget(nodeArr[i].children, id);
            if (node) {
              return node;
            }
          }
        }
      }
    },
    // 新增数据模型
    addModel(node) {
      this.isAddOrUpdateModel = true;
      this.$nextTick(() => {
        this.$refs["addOrUpdateModelRef"].init(undefined, node);
      });
    },
    // 新增文件夹
    addOrUpdateFolder(sign, node) {
      this.isAddOrUpdateFolder = true;
      this.$nextTick(() => {
        this.$refs["addOrUpdateFolderRef"].init(
          sign,
          node,
          this.ownTreeData,
          "account"
        );
      });
    },

    // 点击菜单项触发的事件
    handleMenuClick(menu, node) {
      const menuName = menu.name;
      if (menuName === "新增分类" || menuName === "添加子目录") {
        this.handleAddOrUpdateFolder("add", node);
      } else if (menuName === "新增数字样机") {
        this.handleAddOrUpdateFile("add", node);
      } else if (menuName === "编辑" && node.type === 0) {
        this.handleAddOrUpdateFolder("edit", node);
      } else if (menuName === "编辑" && node.type === 1) {
        this.handleAddOrUpdateFile("edit", node);
      } else if (menuName === "复制") {
        this.handleCopyFile(node);
      } else if (menuName === "删除") {
        this.handleDelete(node);
      }
    },
    // 移动树节点的顺序
    moveNodeOrder(draggingNode, dropNode, dropType) {
      moveTreeNodeOrder({
        movedNodeId: draggingNode.data.id, // 被移动节点的id
        referenceNodeId: dropNode.data.id, // 参照节点的id
        position: dropType == "after" ? 1 : dropType == "before" ? -1 : 0, // 相对位置，before:-1,into:0,after:1
        ancestors: draggingNode.data.data.ancestors, // 祖先
        folderChildrenOrder: {
          parentId:
            dropType == "inner" ? dropNode.data.id : dropNode.data.parentId, // 父级id
          siblingIds:
            dropType == "inner"
              ? Array.from(dropNode.childNodes).map((item) => item.data.id)
              : Array.from(dropNode.parent.childNodes).map(
                (item) => item.data.id
              ),
        },
      }).then((response) => {
        if (response.code == 200) {
          this.$message.success(
            this.$toolHandle.getI18nName(
              this.$zh.setup.responseText,
              this.$en.setup.responseText,
              this.$i18n.locale,
              "success"
            )
          );
          this.getList();
        }
      });
    },
    // 点击左侧列表项,右侧展示详细内容
    showComponent(menu) {
      if (menu.type == "apiSchema") {
        this.isOverview = false;
        this.isFolderDetail = false;
      } else {
        this.isOverview = true;
      }
    },
    // 新增/编辑目录的弹框
    handleCreateDirectory(row, treeList) {
      // 阻止事件冒泡,阻止由内向外触发事件
      event.stopPropagation();
      this.isCreateDirectory = true;
      this.$nextTick(() => {
        this.$refs.createDirectoryRef.init(row, treeList);
      });
    },

    // 点击树节点，右侧展示详细信息
    nodeClick(node) {
      if (node == undefined) {
        return;
      }
      this.selectedNodeInfo = node;
      this.currentNodeKey = node.id;
      this.$nextTick(() => {
        this.$refs.leftTreeRef.$refs.treeRef.setCurrentKey(this.currentNodeKey)
      })
      this.$store.commit("modelManageTool/SET_SELECTED_NODE_ID", { moduleName: 'machine', id: node.id })
      if (node.type == 0) {
        // 点击的文件夹
        this.isFolder = true;
        this.isFile = false;
        this.$store.commit("modelManageTool/SET_EXPANDED_NODE_IDS", { moduleName: 'machine', idList: Array.from(new Set([...this.defaultExpandedKeys, node.id])) })
      } else {
        // 点击的文件
        this.isFolder = false;
        this.isFile = true;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.digital-machine-manage {
  width: 100%;
  height: 100%;
  display: flex;

  .dmm-left {
    width: calc(20% - 1.5px);
    min-height: 100%;
    max-height: 100%;
    padding: 0.5%;
    box-sizing: border-box;
    border-right: 1px solid var(--ui-border-color-base);
  }

  .dmm-right {
    width: 80%;
    height: 100%;
    padding: 0.5%;
    // display: flex;
    // justify-content: center;
    box-sizing: border-box;
    overflow: auto;
  }
}
</style>